package controller

import (
	"gateway-server/internal/registry"
	"gateway-server/pkg/beego"
	"net/http/httputil"
	"net/url"
)

type ModelController struct {
	beego.BeeController
}

func NewModelController() ModelController {
	return ModelController{}
}

const UserJwtSalt = "user-jwt-salt"

func (mc *ModelController) ChatCompletionsHandler() {
	model := mc.GetString("model")
	if model == "" {
		mc.Ctx.Output.SetStatus(400)
		mc.Ctx.Output.Body([]byte("model is required"))
		return
	}
	etcdRegistry := mc.Ctx.Request.Context().Value(registry.EtcdRegistryContextKey).(registry.EtcdRegistry)
	services, _ := etcdRegistry.DiscoverServiceInstances("model")
	if len(services) == 0 {
		mc.CustomAbort(404, "no model service found")
	}
	target := "http://" + services[0]
	u, _ := url.Parse(target)
	proxy := httputil.NewSingleHostReverseProxy(u)
	proxy.ServeHTTP(mc.Ctx.ResponseWriter, mc.Ctx.Request)
	//userJwt := beego.GetUserJWT(mc.Ctx)
	//
	//// 先从redis读取 该userJwt对应的 apiKey 若没有再生成
	//modelName := "gpt-3.5-turbo"
	//g := utils.NewApiKeyGenerator(userJwt, modelName, UserJwtSalt)
	//apiKey, err := g.Generate()
	//if err != nil {
	//	logger.Default.Errorf("Failed to generate API key: %v", err)
	//	mc.Ctx.Output.SetStatus(400)
	//	mc.Ctx.Output.Body([]byte(err.Error()))
	//}
	//logger.Default.Infof("API Key: %s", apiKey)
	//// 将apiKey缓存到redis里面
	//
	//if err := utils.CheckChatCompletionsApiKey(apiKey); err != nil {
	//	mc.Ctx.Output.SetStatus(400)
	//	mc.Ctx.Output.Body([]byte(err.Error()))
	//}
	//
	//// 重写请求头部分的 AuthorizationHeader 替换为重新生成apiKey<jwt>
	//req := mc.Ctx.Request
	//
	////// 打印所有 Header
	////if err := types.HasAllChatRequestHeaders(req); err != nil {
	////	logger.Default.Errorf("Missing required headers")
	////	gc.Ctx.Output.SetStatus(400)
	////	gc.Ctx.Output.Body([]byte(err.Error()))
	////	return
	////}
	//
	//// 读取 Body 并打印
	//bodyBytes, err := io.ReadAll(req.Body)
	//if err != nil {
	//	logger.Default.Errorf("Failed to read body: %v", err)
	//	mc.Ctx.Output.SetStatus(500)
	//	return
	//}
	//
	//// 重新设置 Body，以便后续读取（如绑定 JSON）
	//req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
	//
	//// 打印 Body
	//logger.Default.Infof("Body: %s", string(bodyBytes))
	//// 改写为直接从连接池中获取一个当前可用的连接
	//
	//// 示例响应
	//mc.Ctx.Output.Body(bodyBytes)
}
